<template>
  <!-- 分页器 -->
  <div class="paging">
    <div class="paging-container">
      <!-- 左箭头 -->
      <div
        :class="props.paging.page == 1 ? 'page-forbidden' : ''"
        @click="goBakc(-1, props.paging.page)"
      >
        <van-icon name="arrow-left" />
      </div>
      <!-- 分页块 -->
      <div
        v-for="(item, index) in Math.ceil(total / props.paging.limit)"
        :key="index"
        :class="index + 1 == props.paging.page ? 'page-active' : ''"
        @click="setPage(index + 1)"
      >
        <span>{{ index + 1 }}</span>
      </div>
      <!-- 右箭头 -->
      <div
        :class="
          props.paging.page == Math.ceil(total / props.paging.limit)
            ? 'page-forbidden'
            : ''
        "
        @click="goBakc(1, props.paging.page)"
      >
        <van-icon name="arrow" />
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * v-model 当前页码 page
 * page-count 总页码(总返回数据/limit)
 * total-items 总记录数
 * show-page-size 显示的页码个数
 *
 * change 点击页码触发事件
 */
import { computed } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";

const store = useStore();
const route = useRoute();

// 接收父组件传递的初始化值
const props = defineProps({
  paging: {
    limit: Number,
    page: Number,
    total: Number,
  },
});

// 搜索总条数 (直接传递数据会延迟一次赋值 原因未知)
const total = computed(() => {
  // 如果页面是歌单列表 则通过父元素获取
  if (route.path == "/findMusic/songList") return props.paging.total;
  return store.state.m_search.searchData.result.songCount;
});

// 点击页码事件
const setPage = (page) => {
  if (page == props.paging.page) return;
  // 如果页面是歌单列表 则返回顶部
  if (route.path == "/findMusic/songList")
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  props.paging.page = page;
};

// 左右箭头事件
const goBakc = (num, index) => {
  props.paging.page = index + num;
};
</script>
<style lang='less'>
.paging {
  position: relative;
  bottom: 50px;
  width: 100%;
  margin-bottom: 50px;
  display: flex;
  justify-content: center;

  .paging-container {
    display: flex;

    // 禁用
    .page-forbidden {
      background-color: #ffffff;
      color: #cbcbcb;
      &:hover {
        cursor: no-drop;
        background-color: #ffffff;
        color: #cbcbcb;
      }
    }

    .page-active {
      background-color: #ec4141;
      color: white;

      &:hover {
        cursor: default;
        background-color: #ec4141;
        color: white;
      }
    }

    div {
      text-align: center;
      width: 22px;
      height: 22px;
      line-height: 22px;
      border-radius: 4px;
      background-color: #ffffff;
      border: 1px solid #e6e6e6;
      margin-left: 3px;
      transition: all 0.1s;

      &:hover {
        cursor: pointer;
        background-color: #f4f4f4;
      }
    }
  }
}
</style>